<template>
	<view v-if="loaded" class="container">
		<view class="nav-wrap">
			<uni-navbar
				@tabClick="tabClick"
				:navList="navList"
				:tabCurrentIndex="tabCurrentIndex"
				:borderColor="themeStyles.lightMainColor"
			></uni-navbar>
		</view>
		<view class="content">
			<!-- 空白页 -->
			<empty
				v-if="loadingType !== 'loading' && !goodsList.length"
				:src="baseTemplateFileUri + 'image/emptyStatus/common.png'"
			></empty>
			<view v-else class="goods-wrap">
				<!-- 正在参与的 begin -->
				<!-- <col-goodsList
          :goodsList="goodsList"
          :activityType="activityType"
        ></col-goodsList> -->
				<uni-m-goods-col
					v-for="(item, index) in goodsList"
					:key="index"
					:goods="item"
					:goodsPrice="item.priceStr.split('.')"
					:latePrice="item.priceOut"
					:additionalText="viewAdditionalText(item)"
					:routeLink="
						`/pages/activity/pages/bargain?joinId=${item.bargainInitiatorId}`
					"
					priceFavorText="最低"
				>
					<view
						slot="goodsType"
						:style="themeStyles.textAdronmentColor"
					>
						<view
							v-if="item.filtrateStatus === 0"
							class="goods-countdown"
						>
							<text>距离结束</text>
							<uni-countdown
								:showDay="false"
								:color="themeStyles.adronmentColor"
								:splitorColor="themeStyles.adronmentColor"
								:hour="item.countdown.hh"
								:minute="item.countdown.mm"
								:second="item.countdown.ss"
							>
							</uni-countdown>
						</view>
						<template v-else>
							<view>
								<template v-if="item.status === 0"
									>已支付</template
								>
								<template v-else>未支付</template>
							</view>
						</template>
					</view>
					<view slot="metaRight">
						<button
							v-if="item.bargainStatus === 0"
							:style="{
								color: themeStyles.auxiliaryColor,
								background: `linear-gradient(160deg, ${themeStyles.mainColor}80, ${themeStyles.mainColor})`
							}"
							class="goods-btn"
						>
							砍
						</button>
						<button
							v-else-if="
								item.bargainStatus === 1 ||
									item.bargainStatus === 2
							"
							@click.stop="
								nowPay(item.bargainInitiatorId, item.orderId,item)
							"
							:style="themeStyles.btnAuxiliaryColor"
							class="ghost-btn"
						>
							<text class="ghost-btn-text">付款</text>
						</button>
					</view>
				</uni-m-goods-col>
				<!-- 正在参与的 end -->
				<uni-load-more :status="loadingType"></uni-load-more>
			</view>
		</view>
		<!-- 选择支付方式弹层 -->
		<pop-pay
			type="10"
			:showPopPay="showPopPay"
			:orderInfo="orderInfo"
			@close="closePopPay"
			@select-pay-type="selectPayMoneyTypeAfter"
			@payBefore="callPayBefore"
			@payFn="callPay"
			@paySuccessAfter="paySuccessAfter"
			@payFailAfter="payFailAfter"></pop-pay>
	</view>
</template>

<script>
import {
	queryMybargainList,
	addBargainOrder
} from "@/lib/api/bargainServer/initiator";

/**  components begin */
import uniMGoodsCol from "@/components/goods/uniMGoodsCol";
import uniNavbar from "@/components/uniNavbar/uniNavbar";
import empty from "@/components/empty";
import uniLoadMore from "@/components/uniLoadMore/uniLoadMore";
import uniCountdown from "@/components/uniCountdown/uniCountdown.vue";
/* 选择支付方式弹层 */
import popPay from "@/components/popPay";
/**  components end */

import bargainMixin from "@/mixins/activity/bargain";
import payMixin from "@/mixins/pay";

let currentPage = 1;
export default {
	mixins: [
		bargainMixin,
		payMixin
	],
	components: {
		uniNavbar,
		uniMGoodsCol,
		empty,
		uniCountdown,
		uniLoadMore,
		popPay
	},
	data() {
		return {
			navList: [
				{
					text: "进行中"
				},
				{
					text: "已完成"
				}
			],
			tabCurrentIndex: 0,
			goodsList: [],
			activityType: 5
		};
	},

	async onLoad() {
		currentPage = 1;
	},

	onShow() {
		this.getMyBargainList();
	},

	//下拉刷新
	async onPullDownRefresh() {
		currentPage = 1;
		await this.getMyBargainList();
		uni.stopPullDownRefresh();
	},

	//加载更多
	onReachBottom() {
		if (this.loadingType === "more") {
			currentPage++;
			this.getMyBargainList();
		}
	},

	methods: {
		tabClick(index) {
			if (this.tabCurrentIndex === index) {
				return;
			}
			currentPage = 1;
			this.tabCurrentIndex = index;
			this.getMyBargainList();
		},

		viewAdditionalText(item) {
			if (item.filtrateStatus === 0) {
				return `已砍${item.downPrice || 0}元，还差${item.shortPrice ||
					0}元`;
			} else {
				return `砍价完成，已砍${item.downPrice || 0}元`;
			}
		},

		// 获取我的砍价列表
		async getMyBargainList() {
			this.loadingType = "loading";
			const propsData = {
				currentPage,
				filtrateStatus: this.tabCurrentIndex
			};

			try {
				const res = await queryMybargainList(propsData);

				// if (res.data.list.length) {
				//   res.data.list.forEach((item, index) => {
				//     res.data.list[index].price = item.priceStr.split(".");
				//   });
				// }
				// res.data.list = this.splitGoodsPrice(
				//   res.data.list,
				//   "price",
				//   "priceStr"
				// );

				if (currentPage === 1) {
					this.goodsList = res.data.list;
				} else {
					this.goodsList = this.goodsList.concat(res.data.list);
				}

				const noMore = this.goodsList.length >= res.data.total;
				this.loadingType = noMore ? "noMore" : "more";
				this.loaded = true;
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "加载失败");
				uni.navigateBack();
			}
		},
		//  支付之前
		async callPayBefore(val,callback){
			let orderId = "";
			try {
				orderId =
					this.orderInfo.orderId ||
					(await this.createBargainOrder(this.orderInfo.bargainInitiatorId));
				//
				this.orderId = orderId;
			} catch (error) {
				console.log("error", error);
				//await this.$api.showToast(error.resultInfo || "操作失败");
			}
			//
			callback(orderId);
		},
		// 开始支付
		async callPay(val,callback){
			let payInfo;
			try {
				payInfo = await this.onPay(this.orderId,this.payMoneyType);
				//uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} catch (error) {
				console.log("error", error);
				//this.$api.showToast(error.resultInfo || "支付失败");
				//uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			}
			//支付之后
			callback(payInfo);
		},
		// 付款成功之后
		paySuccessAfter(){
			//到店订单15 or 线上订单10   
			let orderType = this.orderInfo.type;
			let orderStatus = orderType===10?4:3;
			uni.redirectTo({
				url: `/pages/user/pages/order/orderList?orderStatus=${orderStatus}`
			});
		},
		//  支付失败之后
		payFailAfter(){
			let orderStatus = 1;
			uni.redirectTo({
				url: `/pages/user/pages/order/orderList?orderStatus=${orderStatus}`
			});
		},
		// 付款
        async nowPay(bargainInitiatorId, orderId = '',bargainInfo) {
			// 砍价详情
			this.orderInfo = null;
			this.orderInfo = bargainInfo;
			//支付弹层的支付金额
			this.orderInfo.totalFeeStr = this.ZZaddNumZero(this.orderInfo.nowPrice);
			console.log(this.orderInfo);
			// 打开支付弹层
			this.openPopPay();
			return;
			//
            /* try {
                orderId = orderId || (await this.createBargainOrder(bargainInitiatorId));
            } catch (error) {
                console.log("error", error);
                await this.$api.showToast(error.resultInfo || "操作失败");
                return;
            }

            try {
                await this.onPay(orderId);
                uni.redirectTo("/pages/user/pages/order/orderList");
            } catch (error) {
                console.log("error", error);
                this.$api.showToast(error.resultInfo || "支付失败");
                uni.reLaunch({
                    url: "/pages/user/pages/order/orderList"
                });
            } */
        },
	}
};
</script>

<style lang="scss" scoped>
@import "@/pages/activity/styles/myBargain.scss";
</style>
